﻿using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;

namespace Logistics
{
    public static class Logger
    {
        static object objLock = new object();
        public static string FileName { get; set; }
        public static string FilePath { get; set; }
        static Logger()
        {
            var objThread = new Thread(new ThreadStart(DeleteFiles));
            objThread.IsBackground = true;
            objThread.Start();
        }
        public static void WriteLine(string msg)
        {
            lock (objLock)
            {
                string logPath = Path.Combine(Application.StartupPath, "Logger");
                if (!Directory.Exists(logPath))
                    Directory.CreateDirectory(logPath);
                var logFile = Path.Combine(logPath, FileName + ".log");
                FilePath = logFile;
                FileStream fw = null;
                BinaryWriter bw = null;
                try
                {
                    fw = new FileStream(logFile.ToString(), FileMode.Append, FileAccess.Write);
                    bw = new BinaryWriter(fw);
                    var time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    var msginfo = string.Format("{0}\t\t{1}\r\n", time, msg);
                    var buf = Encoding.UTF8.GetBytes(msginfo);
                    bw.Write(buf);
                    //Console.Write(msginfo);
                    Debug.Write(msginfo);
                }
                catch (Exception) { }
                finally
                {
                    try
                    {
                        fw.Close();
                        bw.Close();
                    }
                    catch { }
                }
            }
        }

        private static void DeleteFiles()
        {
            while (true)
            {
                try
                {
                    var icount = 0;
                    Thread.Sleep(30 * 1000);
                    var logPath = Path.Combine(Application.StartupPath, "Logger");
                    if (!Directory.Exists(logPath))
                        continue;
                    var fileList = Directory.GetFiles(logPath);
                    Array.Reverse(fileList);
                    foreach (var item in fileList)
                    {
                        if (icount > 10)
                        {
                            if (File.Exists(item))
                                File.Delete(item);
                        }
                        icount++;
                    }
                }
                catch { }
            }
        }
    }
}
